// 加载共通参数
import Setting from '@/utils/common.js';
// 默认--正式环境
let BASE_URL = Setting.settingConstant.BASE_URL;
let PROJECT_NAME = Setting.settingConstant.PROJECT_NAME;  //项目名称

// 如果是--测试环境
if(Setting.settingConstant.CONFIG_FLAG != 1) {
	PROJECT_NAME = Setting.settingConstant.DEV_PROJECT_NAME;  //项目名称
}

// API的常量
const apiNames = {
	"ALIPAY_JSAPI_OPENID": BASE_URL + PROJECT_NAME + "/aliPay/getOpenid/",   // 根据授权code，获取人员的openid -{code}GET
	"IS_JUMP": BASE_URL + PROJECT_NAME + "/isjump",							 // 是否跳转 -POST
	"APPOINT": BASE_URL + PROJECT_NAME + "/appoint",						// 预约 -POST
	"TENCENT_GEO": BASE_URL + PROJECT_NAME + "/location/amap/geo",			// 地址解析（地址获取坐标） {address}-POST----- form-data
};

// 封装请求-json传参
const myHttps = (url, data = {}, method, header = {}) => {
	return new Promise((resolve, reject) => {
		// 打开【加载】
		uni.showLoading();
		uni.request({
			url: url,
			method: method || 'GET',
			header: {
				'Content-type': 'application/json;charset=UTF-8',
				'Access-Control-Allow-Origin': '*',
				'token': uni.getStorageSync(Setting.settingConstant.SPA_TOKEN) || ''
			} || header,
			data: data || {},
			withCredentials: true,
			success: (res) => {
				// 关闭【加载】
				uni.hideLoading();
				resolve(res.data);
				if(res.data && res.data.code == 300) {
					//缓存用户登陆状态--登录状态变更
					uni.setStorage({
					    key: Setting.settingConstant.SPA_LOGIN,  
					    data: false,  
					}) 
					uni.showToast({
						title: 'Token过期了~',
						icon: 'none'
					});
					// 跳转到登录页面
					/* uni.navigateTo({  
						url: '/pages/public/login'
					}) */
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '请求接口API失败！',
					icon: 'none'
				});
				reject(err);
			}
		})
	})
}

// 封装请求--formData传参
const myFormDataHttps = (urls, formData, method) => {
	return new Promise((resolve, reject) => {
		// 打开【加载】
		uni.showLoading();
		uni.request({
			url: urls,
			method: method || 'POST',
			data: formData,
			header: {
			    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',   // 根据后台接口要求设置Content-Type
				'Access-Control-Allow-Origin': '*',
				'token': uni.getStorageSync(Setting.settingConstant.SPA_TOKEN) || ''
			},
			withCredentials: true,
			success: (res) => {
				// 关闭【加载】
				uni.hideLoading();
				resolve(res.data);
				if(res.data && res.data.code == 300) {
					//缓存用户登陆状态--登录状态变更
					uni.setStorage({
					    key: Setting.settingConstant.SPA_LOGIN,  
					    data: false,  
					}) 
					uni.showToast({
						title: 'Token过期了~',
						icon: 'none'
					});
					// 跳转到登录页面
					/* uni.navigateTo({  
						url: '/pages/public/login'
					}) */
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '请求接口API失败！',
					icon: 'none'
				});
				reject(err);
			}
		})
	})
}

// 对外导出
export default {
	myHttps,
	myFormDataHttps,
	apiNames
}